<!-- 储值管理 -->
<template>
  <div class="stored_value_manager">
    <el-main class="base_main_content">
      <div class="base_screen_header">
        <div style="display: flex; flex-direction: column; align-items: start; gap:5px">
          <el-button type="primary" @click="add">单个用户储值</el-button>
          <el-button type="primary" @click="openImport">批量用户储值</el-button>
          <el-button type="primary" @click="openCard">储值卡管理</el-button>
        </div>
        <el-form :inline="true" class="base_search_form" @submit.prevent>
          <el-form-item>
            <el-select v-model="outTime" @change="searchOutTime" placeholder="过期时间排序" clearable>
              <el-option v-for="(item, index) in outTimeOptions" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="date" type="daterange" range-separator="~" start-placeholder="开始时间"
              end-placeholder="结束时间" value-format="YYYY-MM-DD" @change="searchDate" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="phone" @keyup[native].enter="searchPhone" @change="searchPhone" placeholder="手机号" clearable
              :suffix-icon="Search" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="reason" @keyup[native].enter="searchReason" @change="searchReason" placeholder="说明"
              clearable :suffix-icon="Search" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="remark" @keyup[native].enter="searchRemark" @change="searchRemark" placeholder="备注"
              clearable :suffix-icon="Search" />
          </el-form-item>
        </el-form>
      </div>
      <el-row>
        <el-col v-for="(item, index) in numList" :key="index" :span="8">
          <div @click="openMoneyList(item.sel)" :class="{ td_money_item: true, td_money_item_sel: item.sel }">
            <div class="tdm_title">{{ item.label }}</div>
            <h2>{{ item.total }}</h2>
          </div>
        </el-col>
      </el-row>
      <div class="base_main_margin_top">
        <StatusBar :data="statusList" default="all" />
      </div>
      <div class="base_main_header">
        <el-button type="primary" text @click="delRefuseData">删除未通过记录</el-button>
        <el-button type="primary" text @click="exportData">导出</el-button>
      </div>
      <el-tabs v-model="type" class="stored_order_tabs" @tab-change="tabChange">
        <el-tab-pane name="deposit">
          <template #label>
            <el-badge>
              <span>储值金额列表</span>
            </el-badge>
          </template>
        </el-tab-pane>
        <el-tab-pane name="freeze">
          <template #label>
            <el-badge>
              <span>冻结金额列表</span>
            </el-badge>
          </template>
        </el-tab-pane>
      </el-tabs>
      <div class="base_main_margin_top">
        <DataCollectTable :data="data" :config="type === 'freeze' ? freezeConfig : depositConfig" :total="total"
          @operationsHander="opHander.receive" />
      </div>
      <el-dialog v-model="dialogVisible" title="单个用户储值" width="35%" top="20vh" class="base_dialog"
        @open="resetForm(formRef)">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="用户手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入用户手机号" />
          </el-form-item>
          <el-form-item label="储值金额" prop="changeMoney">
            <el-input-number v-model.number="form.changeMoney" placeholder="单位元。正数为增加，负数为减少" :precision="2"
              :controls="false" controls-position="right" />
          </el-form-item>
          <el-form-item label="金额类型" prop="depositType">
            <el-radio-group v-model="form.depositType">
              <el-radio label="1048001">可用金额</el-radio>
              <el-radio label="1048002">冻结金额</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="姓名/单位" prop="persionName">
            <el-input v-model="form.persionName" clearable placeholder="请输入姓名或单位名称" resize="none" />
          </el-form-item>
          <el-form-item label="摘要" prop="changeReason">
            <el-input v-model="form.changeReason" type="textarea" clearable placeholder="用户展示" resize="none" />
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" clearable placeholder="后台展示" resize="none" />
          </el-form-item>
          <el-form-item label="失效日期">
            <el-date-picker v-model="form.depositExpireTime" type="date" placeholder="若不填，无失效日期，可以为2099-12-31日"
              value-format="YYYY-MM-DD" clearable />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </span>
        </template>
      </el-dialog>
    </el-main>
  </div>
</template>

<script setup>
import StatusBar from "@com/StatusBar.vue";
import { $msg, $box } from "@ui/msg";
import { ref, reactive } from "vue";
import { Search } from "@element-plus/icons-vue";
import useRoute from "@util/router";
import DataCollectTable from "@com/table/DataCollectTable.vue";
import {
  OP_KEY,
  COLUMN_TYPE,
  OPERATIONS,
  operationsHander,
} from "@com/table/tableOperations";
import $ from "@util/base";
import api from "@api/deposit";

const route = useRoute();

route.watchRouter("depositmanager", () => {
  getData();
});

const outTime = ref(route.query().outtime || '');

const outTimeOptions = ref([
  { label: "正序", value: "1" },
  { label: "倒序", value: "2" }
])

function searchOutTime(val) {
  route.replaceQuery("outtime", val);
}

const statusList = reactive([
  {
    label: "全部",
    value: "all",
    total: 0,
  },
  {
    label: "待审批",
    value: "1047002",
    total: 0,
  },
  {
    label: "已通过",
    value: "1047001",
    total: 0,
  },
  // {
  //   label: "已驳回",
  //   value: "1047003",
  //   total: 0,
  // },
]);

const numList = reactive([
  // {
  //   label: "储值总额",
  //   total: 0,
  //   sel: false,
  // },
  {
    label: "储值余额（元）",
    total: 0,
    sel: "deposit",
  },
  {
    label: "冻结余额（元）",
    total: 0,
    sel: "freeze",
  },
  {
    label: "储值用户（个）",
    total: 0,
    sel: "user",
  },
]);

function openMoneyList(val) {
  if (val) {
    route.push({
      name: "depositmoneylist",
      query: { type: val },
    });
  }
}

const data = ref([]);
const total = ref(0);

function getOperations(data) {
  if (data.validStatus == "1047003") {
    return [OPERATIONS.check, OPERATIONS.del];
  } else {
    return [OPERATIONS.check];
  }
}

const depositConfig = {
  showIndex: true,
  operations: {
    label: "操作",
    width: 120,
    operations: getOperations,
  },
  column: [
    {
      label: "姓名",
      prop: "memberName",
      width: 120,
    },
    {
      label: "账号",
      prop: "memberLoginName",
    },
    {
      label: "姓名/单位",
      prop: "persionName",
      width: 130,
    },
    {
      label: "储值余额（元）",
      prop: "balanceMoney",
      width: 130,
    },
    {
      label: "操作储值金额（元）",
      prop: "changeMoney",
      width: 160,
    },
    {
      label: "备注",
      prop: "remark",
    },
    {
      label: "操作人",
      prop: "creatorName",
      width: 120,
    },
    {
      label: "审核状态",
      prop: "validStatusName",
      width: 100,
    },
    {
      label: "过期时间",
      prop: "depositExpireTime",
      width: 180,
    },
    {
      label: "操作时间",
      prop: "createTime",
      width: 180,
    },
  ],
};

const freezeConfig = {
  showIndex: true,
  operations: {
    label: "操作",
    width: 120,
    operations: getOperations,
  },
  column: [
    {
      label: "姓名",
      prop: "memberName",
      width: 120,
    },
    {
      label: "账号",
      prop: "memberLoginName",
    },
    {
      label: "姓名或单位名称",
      prop: "persionName",
      width: 130,
    },
    {
      label: "储值余额（元）",
      prop: "balanceMoney",
      width: 130,
    },
    {
      label: "操作储值金额（元）",
      prop: "changeMoney",
      width: 160,
    },
    {
      label: "备注",
      prop: "remark",
    },
    {
      label: "操作人",
      prop: "creatorName",
      width: 120,
    },
    {
      label: "审核状态",
      prop: "validStatusName",
      width: 100,
    },
    {
      label: "过期时间",
      prop: "depositExpireTime",
      width: 180,
    },
    {
      label: "操作时间",
      prop: "createTime",
      width: 180,
    },
  ],
};

const dialogVisible = ref(false);

const formRef = ref(null);

const form = reactive({
  phone: null,
  changeMoney: null,
  depositType: null,
  changeReason: null,
  remark: null,
  depositExpireTime: null,
});

function show() {
  dialogVisible.value = true;
}

function add() {
  show();
}

const rules = {
  phone: [
    {
      required: true,
      message: "请输入用户手机号",
      trigger: "blur",
    },
  ],
  changeMoney: [
    {
      required: true,
      message: "请输入储值金额",
      trigger: "blur",
    },
    {
      type: "number",
      message: "请输入数字",
    },
  ],
  depositType: [
    {
      required: true,
      message: "请选择金额类型",
      trigger: "change",
    },
  ],
  changeReason: [
    {
      required: true,
      message: "请输入说明",
      trigger: "blur",
    },
  ],
  remark: [
    {
      required: true,
      message: "请输入备注",
      trigger: "blur",
    },
  ],
  persionName: [
    {
      required: false,
      message: "姓名或单位名称",
      trigger: "blur",
    },
  ],
  // depositExpireTime: [
  //   {
  //     required: true,
  //     message: "请选择失效日期",
  //     trigger: "change",
  //   },
  // ],
};

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      userStoredValue(form);
    }
  });
};

function userStoredValue(data) {
  api.add(data, () => {
    $msg.succ("新增成功");
    dialogVisible.value = false;
    getData();
  });
}

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};

function openImport() {
  route.push({
    name: "batchdepositimport",
  });
}

function openCard(){
  route.push({
    name: "depositecard",
  });
}

const opHander = operationsHander();
opHander.install(OP_KEY.check, (data) => {
  route.push({
    name: "depositdetails",
    query: { type: "show", code: data.id },
  });
});

opHander.install(OP_KEY.delete, (data) => {
  $box.open(
    "删除确认",
    `是否删除${data.memberLoginName}账号，该笔储值记录`,
    () => {
      api.delete(data.id, () => {
        $msg.succ("删除成功");
        getData();
      });
    }
  );
});

const type = ref(route.query().type || "deposit");
const phone = ref(route.query().phone || "");
const reason = ref(route.query().reason || "");
const remark = ref(route.query().remark || "");
const date = ref(route.query().date || []);

// const activeName = ref('deposit');

function tabChange(val) {
  route.replaceQuery("type", val);
}

function searchPhone(val) {
  route.replaceQuery("phone", val);
}

function searchReason(val) {
  route.replaceQuery("reason", val);
}

function searchRemark(val) {
  route.replaceQuery("remark", val);
}

function searchDate(val) {
  route.replaceQuery("date", val);
}

getData();
function getData() {
  getList();
  getNum();
  getStatusNum();
}

function getList() {
  let routeQuery = route.query();
  api.list(
    {
      depositType: routeQuery.type === "freeze" ? "1048002" : "1048001",
      phone: routeQuery.phone,
      changeReason: routeQuery.reason,
      remark: routeQuery.remark,
      date: routeQuery.date,
      status: routeQuery.status,
      depositExpireTime: routeQuery.outtime,
      page: routeQuery.p,
      size: routeQuery.s,
    },
    (val) => {
      total.value = val.total;
      data.value = val.list.map((e) => {
        if (e.changeMoney > 0) {
          e.changeMoney = `+${e.changeMoney}`;
        }
        return e;
      });
    }
  );
}

function exportData() {
  let routeQuery = route.query();
  api.exportData(
    {
      depositType: routeQuery.type === "freeze" ? "1048002" : "1048001",
      phone: routeQuery.phone,
      changeReason: routeQuery.reason,
      remark: routeQuery.remark,
      date: routeQuery.date,
      status: routeQuery.status,
      depositExpireTime: routeQuery.outtime,
      page: routeQuery.p,
      size: routeQuery.s,
    },
    (val) => {
      $.download(val.url, "储值列表导出")
    }
  );
}

function delRefuseData() {
  api.delRefuseData(() => {
    $msg.succ("删除成功");
    getData()
  })
}
function getNum() {
  api.num((val) => {
    statusData(val, "num");
  });
}

function getStatusNum() {
  let routeQuery = route.query();
  api.statusNum(
    {
      phone: routeQuery.phone,
      changeReason: routeQuery.reason,
      remark: routeQuery.remark,
      date: routeQuery.date,
      status: routeQuery.status,
    },
    (val) => {
      statusData(val, "status");
    }
  );
}

function statusData(val, type) {
  if (type == "num") {
    //删除储值总额
    val.shift()
    numList.forEach((e, i) => {
      e.total = val[i];
    });
  } else {
    statusList.forEach((e, i) => {
      e.total = val[i];
    });
  }
}
</script>

<style lang="scss">
.stored_value_manager {
  .btn-box {
    width: 340px;

    .el-button {
      &:first-child {
        margin-right: 10px;
      }
    }
  }

  .td_money_item {
    text-align: center;
    border: solid 1px $border;
    border-right: none;

    &:last-child {
      border-right: solid 1px $border;
    }

    .tdm_title {
      height: 50px;
      line-height: 50px;
      border-bottom: solid 1px $border;
      background-color: $background;
    }

    h2 {
      margin: 0;
      height: 80px;
      line-height: 80px;
    }
  }

  .td_money_item_sel {
    cursor: pointer;
  }

  .el-input-number {
    width: 100%;
    max-width: 500px;
    text-align: left;
  }

  .stored_order_tabs {
    // height: 100%;
    --el-tabs-header-height: 60px;
    border: none;

    .el-tabs__header {
      margin: 0;
    }

    .el-badge__content.is-fixed.is-dot {
      right: 0;
      top: 10px;
    }

    .el-tabs__content {
      // height: calc(100% - 60px);
      // overflow: hidden;
      margin: 0;
      padding: 0;
    }
  }

  .el-tabs--top .el-tabs__item.is-top:nth-child(2) {
    padding-left: 20px;
  }
}
</style>

